<template>
  <div class="products-container">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchCategoryId"
            placeholder="选择商品类别"
            clearable
            style="width: 100%"
            @change="handleSearch"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="12" style="text-align: right;">
          <el-button @click="resetSearch" style="margin-right: 10px;">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon> 添加商品
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 商品列表 -->
    <el-table
      :data="productList"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="scope">
          ¥{{ scope.row.price?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="120" />
      <el-table-column prop="categoryId" label="分类" width="120">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="() => changeProductStatus(scope.row)"
          />
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" style="margin-left: 5px;">
            {{ scope.row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      v-model="dialogVisible"
      width="50%"
    >
      <el-form :model="productForm" :rules="rules" label-width="80px" ref="productFormRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="productForm.price" :precision="2" :step="1" :min="0" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="productForm.stock" :min="0" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="productForm.categoryId" placeholder="请选择分类" style="width: 200px;">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="productForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="productForm.description" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProduct">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getProducts, addProduct, updateProduct, deleteProduct as apiDeleteProduct, updateProductStatus } from '@/api/merchant'
import { getAllCategories } from '@/api/category'

// 定义API响应接口
interface ApiResponse<T = any> {
  code: number;
  data: T;
  message: string;
}

// 定义接口类型
interface Product {
  id: number;
  merchantId?: number;
  name: string;
  price: number;
  originalPrice?: number;
  stock: number;
  categoryId: number | null;
  status: number;
  description?: string;
  createTime?: string;
  updateTime?: string;
  deleted?: number;
}

interface Category {
  id: number;
  name: string;
}

// 商品列表
const productList = ref<Product[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const searchCategoryId = ref<number | null>(null)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const productForm = reactive({
  id: 0,
  merchantId: undefined,
  name: '',
  price: 0,
  originalPrice: undefined,
  stock: 0,
  categoryId: null,
  status: 1,
  description: '',
  createTime: undefined,
  updateTime: undefined,
  deleted: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ]
}

// 分类列表
const categoryList = ref<Category[]>([])

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await getAllCategories() as unknown as ApiResponse<Category[]>
    if (response.code === 200) {
      categoryList.value = response.data
      console.log('获取到的分类列表:', categoryList.value)
    } else {
      console.error('获取分类列表失败:', response)
      ElMessage.error('获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取商品列表
const fetchProductList = async () => {
  loading.value = true
  try {
    console.log('开始获取商品列表，参数:', {
      keyword: searchKeyword.value,
      categoryId: searchCategoryId.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'price',
      sortOrder: 'asc'
    })

    const response = await getProducts({
      keyword: searchKeyword.value,
      categoryId: searchCategoryId.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'price',
      sortOrder: 'asc'
    }) as unknown as ApiResponse<{records: Product[], total: number} | Product[]>

    console.log('获取商品列表响应:', response)

    if (response.code === 200) {
      // 检查响应数据结构
      console.log('响应数据结构:', response.data)

      if (response.data && 'records' in response.data) {
        productList.value = response.data.records
        total.value = response.data.total
        console.log('商品列表数据:', productList.value)
      } else if (Array.isArray(response.data)) {
        // 如果直接返回数组
        productList.value = response.data
        total.value = response.data.length
        console.log('商品列表数据(数组):', productList.value)
      } else {
        console.error('响应数据结构不符合预期:', response.data)
        productList.value = []
        total.value = 0
      }
    } else {
      console.error('获取商品列表失败，响应码:', response.code)
      ElMessage.error(`获取商品列表失败: ${response.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchProductList()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchProductList()
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  fetchProductList()
}

// 重置搜索条件
const resetSearch = () => {
  searchKeyword.value = ''
  searchCategoryId.value = null
  currentPage.value = 1
  fetchProductList()
}

// 打开添加对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  Object.assign(productForm, {
    id: 0,
    merchantId: undefined,
    name: '',
    price: 0,
    originalPrice: undefined,
    stock: 0,
    categoryId: null,
    status: 1,
    description: '',
    createTime: undefined,
    updateTime: undefined,
    deleted: 0
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row: Product) => {
  dialogType.value = 'edit'
  Object.assign(productForm, { ...row })
  dialogVisible.value = true
}

// 保存商品
const saveProduct = async () => {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '保存中...' })

  try {
    console.log('开始保存商品，表单数据:', productForm)

    // 创建一个新对象，不包含mainImage和images字段
    const productData = { ...productForm }

    // 确保不发送这些字段
    delete (productData as any).mainImage
    delete (productData as any).images

    console.log('处理后的表单数据(移除图片字段):', productData)

    if (dialogType.value === 'add') {
      // 添加商品
      console.log('执行添加商品操作')
      const response = await addProduct(productData) as unknown as ApiResponse<Product>
      console.log('添加商品响应:', response)

      if (response.code === 200) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        await fetchProductList()
      } else {
        ElMessage.error(`添加失败: ${response.message || '未知错误'}`)
      }
    } else {
      // 编辑商品
      console.log('执行编辑商品操作，ID:', productForm.id)
      const response = await updateProduct(productForm.id, productData) as unknown as ApiResponse<Product>
      console.log('编辑商品响应:', response)

      if (response.code === 200) {
        ElMessage.success('编辑成功')
        dialogVisible.value = false
        await fetchProductList()
      } else {
        ElMessage.error(`编辑失败: ${response.message || '未知错误'}`)
      }
    }
  } catch (error) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存商品失败，请检查网络连接或刷新页面重试')
  } finally {
    loadingInstance.close()
  }
}

// 删除商品
const deleteProduct = (row: Product) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('执行删除商品操作，ID:', row.id)
      const response = await apiDeleteProduct(row.id) as unknown as ApiResponse<boolean>
      console.log('删除商品响应:', response)

      if (response.code === 200) {
        ElMessage.success('删除成功')
        await fetchProductList()
      } else {
        ElMessage.error(`删除失败: ${response.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败，请检查网络连接或刷新页面重试')
    }
  }).catch(() => {
    // 取消删除
    console.log('用户取消了删除操作')
  })
}

// 更新商品状态
const changeProductStatus = async (row: Product) => {
  try {
    const newStatus = row.status
    console.log('执行更新商品状态操作，ID:', row.id, '新状态:', newStatus)
    const response = await updateProductStatus(row.id, { status: newStatus }) as unknown as ApiResponse<boolean>
    console.log('更新商品状态响应:', response)

    if (response.code === 200) {
      ElMessage.success(`商品已${newStatus === 1 ? '上架' : '下架'}`)
    } else {
      ElMessage.error(`状态更新失败: ${response.message || '未知错误'}`)
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('更新商品状态失败:', error)
    ElMessage.error('更新商品状态失败，请检查网络连接或刷新页面重试')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number | null) => {
  if (!categoryId) return '未分类'
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}

// 页面加载时获取商品列表和分类列表
onMounted(() => {
  fetchCategoryList()
  fetchProductList()
})
</script>

<style scoped>
.products-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
